/*
 * MaxSonarUltrasoundSensor.java
 *
 * Created on April 25, 2008, 2:02 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.ncsu.external_sensors;

import com.sun.spot.core.resources.ResourceUnavailableException;
import com.sun.spot.core.resources.transducers.IIOPin;
import com.sun.spot.edemo.EDemoBoard;


/**
 * Code to drive the LV MaxSonar EZ1 Ultrasound sensor
 * The MaxSonar automatically takes readings ever 50 ms.  
 * Note, robot should be about 14 inches from an obstacle on startup for MaxSonar's calibration process to work correctly.
 * Check white paper for details.
 * @author Douglas McClusky
 */
public class MaxSonarEZ1UltrasoundSensor extends UltrasoundSensor {
    private static final int MAX_SONAR_CONVERSION_FACTOR = 147; //per inch from white paper for this sensor
    
    /** Creates a new instance of MaxSonarEZ1UltrasoundSensor 
     * @param pin - the IIOPin that the PING))) is connected to
     * @param unitOfMeasure - the public index from this class that corresponds to the desired unit of measure
     */
    public MaxSonarEZ1UltrasoundSensor(IIOPin pin, int unitOfLength) {
        input = pin;
        units = unitOfLength;
    }
    
    /**
     * @return the time in milliseconds of the input pulse from the sensor.  This value is the time it takes for
     * the sensor to detect an echo.  See white paper of the sensor for details.
     * @throws ResourceUnavailableException if sensor cannot be detected
     */
    public long getRawValue() throws ResourceUnavailableException {
        long value = EDemoBoard.getInstance().getPulse(input,true,100);
        if (value > 0) {
            return value;
        }
        throw new ResourceUnavailableException("MaxSonarEZ1 not found on pin " + input.getDescription());
    }

    /**
     * @return the distance of the nearest object, in the selected unit of length
     * @throws ResourceUnavailableException if sensor cannot be detected
     */
    public double getConvertedValue() throws ResourceUnavailableException {
        return getRawValue() / MAX_SONAR_CONVERSION_FACTOR * UNITS_PER_METER[INCHES] / UNITS_PER_METER[units];
    }

    public boolean testConnection() {
        return EDemoBoard.getInstance().getPulse(input,true,150) > 0;
    }
}
